gpt4 book ai didi

对象中未填充 Javascript 键

转载 作者:行者123 更新时间:2023-11-30 09:44:30 31 4
gpt4 key购买 nike

我正在尝试创建一个带有键/值的对象,但是当我看到该对象时,键没有正确填充..

我希望键是 - 0,1,2,3 但它显示“索引”作为键。

> categories = ["09/07/2016 00:00","09/07/2016 00:01","09/07/2016 00:02","09/07/2016 00:03","09/07/2016 00:04"]   
["09/07/2016 00:00", "09/07/2016 00:01", "09/07/2016 00:02", "09/07/2016 00:03", "09/07/2016 00:04"]

> rate_1 = [0.41,0.54,0.6,0.7,0.8]
[0.41, 0.54, 0.6, 0.7, 0.8]

> dict = []
[]

> categories.forEach(function(ix,index){console.log(index)
dict.push({index:rate_1[index]})
})
0
1
2
3
4

> JSON.stringify(dict)
"[{"index":0.41},{"index":0.54},{"index":0.6},{"index":0.7},{"index":0.8}]"

最佳答案

你可以通过将 index 放在方括号中来解决这个问题(ES6 语法):

dict.push({ [index]: rate_1[index]})

如果没有这个,index 确实被当作文字,而不是变量。

var categories = ["09/07/2016 00:00","09/07/2016 00:01","09/07/2016 00:02","09/07/2016 00:03","09/07/2016 00:04"];
var rate_1 = [0.41,0.54,0.6,0.7,0.8];
var dict = [];
categories.forEach(function(ix,index){
dict.push({[index]:rate_1[index]})
});
result = JSON.stringify(dict);
console.log(result);

附带说明:这段代码适合使用 map 而不是 forEach,从而节省了显式数组初始化和 push。我只是提供这个信息;这与您的问题无关;-)

var categories = ["09/07/2016 00:00","09/07/2016 00:01","09/07/2016 00:02","09/07/2016 00:03","09/07/2016 00:04"];
var rate_1 = [0.41,0.54,0.6,0.7,0.8];
var dict = categories.map(function(ix,index){
return {[index]:rate_1[index]};
});
result = JSON.stringify(dict);
console.log(result);

关于对象中未填充 Javascript 键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39456141/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com