没执行修改的数组数据被修改?
发布于 5 年前 作者 weijia 9215 次浏览 来自 官方Issues

我从数据库获取到数组赋值给两个不同的数组question[]和errquestion[],从前台点击,会修改question数组中的值,但是errquestion[]没做修改,console.log打印出来两个都被修改了,,,

var errquestion = [];
Page({
  data: {
    question: [],
    //errquestion: [],
    tags0,
    answer'',
    choose:[],
    ansArr:[],

  },
onLoadfunction(options{
    db.collection('xxx').get({
      successres => {
        this.setData({
                  question: res.data[0].question,
                })
        for (let i = 0;i < this.data.question.length;i++){
          errquestion.push(res.data[0].question[i]);
        }
}
  choosefunction(res{
      let chooseArr = this.data.question[mTag].options;
      let nowChecked = 'question[' + mTag + '].options'//setData改变部分数据
      if (chooseArr[index].checked) return//选择当前已经选择的返回
      chooseArr.forEach(item => { //遍历选项,将其他选项设置为false(单选)
          item.checked = false;
      })
      chooseArr[index].checked = true;
            
      this.setData({
           [nowChecked]: chooseArr,
      })
      console.log(errquestion[mTag]);
}
2 回复
就是这样的, 都会被改变
var data = [{c:1,d:2}]
var a = data, b = data
a[0].c = 5
console.log('a :', a)  // => a : [{c:5,d:2}]
console.log('b :', b)  // => b : [{c:5,d:2}]
console.log('data :', data)  // => data : [{c:5,d:2}]

想不被改变就使用JSON.stringify 和 JSON.parse
var data = [{c:1,d:2}]
var a = JSON.parse(JSON.stringify(data)),
b = JSON.parse(JSON.stringify(data))
a[0].c = 5
console.log('a :', a)  // => a : [{c:5,d:2}]
console.log('b :', b)  // => b : [{c:1,d:2}]
console.log('data :', data)  // => data : [{c:1,d:2}]

若认为该回答有用,给回答者点个[ 有用 ],让答案帮助更多的人

“数据库获取到数组赋值给两个不同的数组question[]和errquestion[]”

这部分代码贴一下

回到顶部