簡體   English   中英

如何使用字符串中的數據更新javascript對象?

[英]How can I use data in a string to update a javascript object?

我有以下數據數組:

var ans = 
[
 {"text":"x","response":false},
 {"text":"y","response":false},
 {"text":"z","response":true}
];

var correct = "010"; // I need to add this to the array ans

任何人都可以建議我如何使用正確變量中的數據添加到數組中,以使:

var ans = 
[
 {"text":"x","response":false,"correct":false},
 {"text":"y","response":false,"correct":true},
 {"text":"z","response":true,"correct":false}
];
for(var i=0; i< ans.length; i++) {
    ans[i].correct = correct.charAt(i) == "1";
}
for (var i = 0; i < correct.length; i++) {
    ans[i]["correct"] = correct[i] === "1";
}

您也可以這樣做(使用for-in循環)。

參考: 在JavaScript中遍歷數組嗎?

for(key in ans){
    ans[key].correct = correct.charAt(key) == "1";
}
var ans = 
    [
     {"text":"x","response":false},
     {"text":"y","response":false},
     {"text":"z","response":true}
    ];

var correct = "010";

var sep = correct.split("");

var arr = [];

for (var i = 0; i < sep.length; i++) {
     if (sep[i] == 0) {
       arr.push("false");
      } else {
       arr.push("true");
     }
   }

  var len = ans.length;

 for (var i = 0; i < len; i++) {

        ans[i].correct = arr[i];
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM