1

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

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”中动态添加的数据不会更改。

为什么新数据没有变化?

更新:看到这个小提琴

4

1 回答 1

2

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

由于 freezeObj 是使用 创建Object.freeze()的,因此不允许更改值。此外,您在控制台上没有收到任何错误。JS 在未启用严格模式的情况下不显示错误。我已经修改了小提琴以包含严格模式,你可以看到它在你这样做时抛出和错误data[key].amount = value.amount-perSec;。我还附上了一个小提琴来玩 Object.freeze() 方法,你可以自己试验。

修改过的小提琴

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 小提琴

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.
于 2018-08-15T10:37:42.303 回答