我無法洗掉從 JSON 陣列物件生成的隨機代碼,.splice在洗掉包含所有資料的整行時對我來說作業得很好。我有不同的代碼層,在這個例子中,我只需要從“promoCodes”中洗掉隨機生成的值,我總是會收到這個錯誤:
mycodes.slice(mycodes.indexOf(randomcode), 1)
TypeError: mycodes.indexOf is not a function
.JSON
{
"TIER1": {
"rewardSize": 1,
"probability": 0.8,
"numberOfCodes": 2,
"rewardSubtype": 1,
"totalRewardSize": 2,
"promoCodes": [
"TEST1 - 1",
"TEST1 - 2"
]
},
"TIER2": {
"rewardSize": 3,
"probability": 0.25,
"numberOfCodes": 2,
"rewardSubtype": 2,
"totalRewardSize": 6,
"promoCodes": [
"TEST2 - 1",
"TEST2 - 2"
]
},
"TIER3": {
"rewardSize": 10,
"probability": 0.15,
"numberOfCodes": 2,
"rewardSubtype": 3,
"totalRewardSize": 20,
"promoCodes": [
"TEST3 - 1",
"TEST3 - 2"
]
},
"TIER4": {
"rewardSize": 25,
"probability": 0.05,
"numberOfCodes": 2,
"rewardSubtype": 4,
"totalRewardSize": 50,
"promoCodes": [
"TEST4 - 1",
"TEST4 - 2"
]
},
"TIER5": {
"rewardSize": 50,
"probability": 0.04,
"numberOfCodes": 2,
"rewardSubtype": 5,
"totalRewardSize": 100,
"promoCodes": [
"TEST5 - 1",
"TEST5 - 2"
]
},
"TIER6": {
"rewardSize": 100,
"probability": 0.01,
"numberOfCodes": 2,
"rewardSubtype": 6,
"totalRewardSize": 200,
"promoCodes": [
"TEST6 - 1",
"TEST6 - 2"
]
},
"TIER7": {
"rewardSize": 1000,
"probability": 0.001,
"numberOfCodes": 2,
"totalRewardSize": 2000,
"promoCodes": [
"TEST7 - 1",
"TEST7 - 2"
]
}
}
代碼:
//fs setup
const fs = require('fs');
let rawdata = fs.readFileSync(__dirname '/newtest.json', 'utf8');
let mycodes = JSON.parse(rawdata);
const TIER1 = mycodes['TIER1']['promoCodes']
//something above...
const randomcode = TIER1[Math.floor(Math.random() * TIER1.length)];
console.log(randomcode); //logs random generated code
mycodes.slice(mycodes.indexOf(randomcode), 1)
fs.writeFileSync(__dirname '/newtest.json', JSON.stringify(mycodes, 0, 4), 'utf8')
delete我試過了:
但在delete [randomcode];
delete mycodes[randomcode];
這種情況下沒有做任何事情,因為它永遠不會從檔案中洗掉。
uj5u.com熱心網友回復:
問題是您試圖slice在一個物件上呼叫該方法object,mycodes但這不會發生,因為該方法slice僅為標準內置物件定義。StringArray
一種解決方案
const fs = require('fs');
let rawdata = fs.readFileSync(__dirname '/newtest.json', 'utf8');
let mycodes = JSON.parse(rawdata);
const TIER1 = mycodes.TIER1.promoCodes;
const randomcode = TIER1[Math.floor(Math.random() * TIER1.length)];
// get the item from the TIER1 array that matches the randomcode
const foundItem = TIER1.find((item) => item === randomcode);
// remove that item from the TIER1 array
TIER1.splice(TIER1.indexOf(foundItem), 1);
// save the data again to the json file.
fs.writeFileSync(
__dirname '/newtest.json',
JSON.stringify(mycodes, 0, 4),
'utf-8'
);
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/450911.html
標籤:javascript 节点.js 数组 json 片
上一篇:p標簽正在洗掉字串中的換行符
