更改动态添加的js对象的值

时间:2018-08-15 09:58:21

标签: javascript jquery arrays jsobject

我有一个包含一些预定义数据的数组

var data = [
    {amount:20, speed:100},
    {amount:40, speed:50}
];

然后我将数据添加到上述数组

function addMore() {
    data = appendObjTo(data, {amount: 1500,speed:100});
}

function appendObjTo(thatArray, newObj) {
    const frozenObj = Object.freeze(newObj);
    return Object.freeze(thatArray.concat(frozenObj));
}

可以很好地添加数据,但是由于某些原因,我无法更改新数据的值

function runData() {
    perSec = 0;
    $.each(data, function( key, value ) {
        perSecCalc = Math.round(value.speed/60);
        perSec += perSecCalc;
        // Below line works only for predefined objects, but not objects from "addMore()"
        data[key].amount = value.amount-perSec;
    });

    setTimeout(function() {
        runData();
    },1000);
}

“ var data”中的预定义对象被更改时,“ addMore”中动态添加的数据不会更改。

为什么新数据没有变化?

更新: 看到这个fiddle

1 个答案:

答案 0 :(得分:2)

您正在appendObjTo函数中使用Object.freeze。 Object.freeze的定义-Object.freeze()

由于使用Object.freeze()创建了FrozenObj,因此不允许更改这些值。另外,您在控制台上没有任何错误。启用严格模式后,JS没有显示错误。我已经修改了小提琴以使其包含严格模式,并且您在执行data[key].amount = value.amount-perSec;时可以看到它抛出错误。我还附加了一个小提琴来玩Object.freeze()方法,您可以自己尝试。

Modified fiddle

JS

(function () {

"use strict";

var data = [
    {amount:20, speed:100}
];


function runData() {
    var perSec = 0;
    $.each(data, function( key, value ) {
        var perSecCalc = Math.round(value.speed/60);
        perSec += perSecCalc;
        // Below line works only for predefined objects, but not objects from "addMore()"
        data[key].amount = value.amount-perSec;
        $('#test').prepend(data[key].amount+'<br>');
    });

    setTimeout(function() {
        runData();
    },1000);
}

function appendObjTo(thatArray, newObj) {
  const frozenObj = Object.freeze(newObj);
  return Object.freeze(thatArray.concat(frozenObj));
}

function addMore() {
    data = appendObjTo(data, {amount: 1500,speed:100});
}

setTimeout(function() { addMore(); },1500);

runData();


})();

Object.freeze fiddle

var arr = [10, 20, 30];
console.log(arr);

arr = Object.freeze(arr.concat([40, 50]));
console.log(arr);

arr[3] = 80;
console.log(arr); // doesn't change

// arr.push(60); // error, cannot add property 5, object is not extensible

arr = Object.freeze(arr.concat([{ x: 100 }]));
console.log(arr);

arr[5].x = 200;
console.log(arr); // changes, as Object.freeze only locks the first level values.