【问题标题】:Why is javascript array being populate with key values为什么用键值填充javascript数组
【发布时间】:2017-02-08 05:22:03
【问题描述】:

我有一个空数组,我想用我从循环中获得的值填充它:

var testArray = [];
var data = [
    {values:[3,4,3,4]},
    {values:[3434]},
    {values:[3,43,4]}
];

for ( i = 0; i < data.length; i++ ) {
    amounts = data[i].values.length;
    console.log(amounts);
    testArray.push(amounts);
}
console.log(testArray);

当我 console.log() 'amounts' 变量时,我得到了我所有整数的列表,但是如果我 console.log() 'testArray' 变量,我得到一个键值数组,例如 testArray = [ 0 :126 等]。

为什么我的数组不只是填充金额?

【问题讨论】:

  • 数组确实有数字索引吗?
  • 请发一个 jsfiddle..
  • 这里正在工作 jsfiddle jsfiddle.net/w9k9dy4e 。不确定您的数据对象的外观。
  • 你能显示data数组吗?因为我做了一个,它正在工作
  • @JordanBarber — console 有自己的表达方式,console.log(JSON.stringify(testArray)) 应该会显示您预期的结果:)

标签: javascript arrays for-loop array-push


【解决方案1】:

这是因为您将每个 valueslength 存储到 amounts 中,然后将 amounts 推送到 testArray 中,因此结果将是一个长度数组而不是值。如果你尝试直接推送values,你会得到一个二维数组,你应该像这样使用concat

var testArray = [];
var data = [
    {values:[3,4,3,4]},
    {values:[3434]},
    {values:[3,43,4]}
];

for ( i = 0; i < data.length; i++ ) {
    amounts = data[i].values; // amounts should be the values array not its length
  
    testArray = testArray.concat(amounts); // concat testArray with the current values array and store it back into testArray to continue accumulatig the result
}

console.log(testArray);

【讨论】:

    猜你喜欢
    • 2023-02-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-24
    • 2021-01-14
    • 2014-10-03
    • 1970-01-01
    相关资源
    最近更新 更多