Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
177 views
in Technique[技术] by (71.8m points)

js对象取值

  var obj ={
        name:'nnn',
        age:22,
        job:'worker'
    };
  
    var arr=[
        'name',
        'age',
        'job'
    ];

    for (var i=0 ;i<arr.length;i++){
        document.writeln(arr[i]+':'+obj[arr[i]]);
    };//有值
     for (var i=0 ;i<arr.length;i++){
        document.writeln(arr[i]+':'+obj.arr[i]);
    };//没值,不报错
    

这两种有什么不同,出现上面的情况的原因是什么,请大神帮我解惑


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

你确定不报错? 看看控制台信息
obj.arr[i] 这个调用是错的
obj.arr 不存在, 等于 undefined
undefined[i] 肯定会出错


首先 obj 和 arr 都可以用 [] 的方式来取值:
这个例子的两种做法不同点在于:
obj[arr[i]] 是先取 arr[i] 再赋值给 obj[]:

arr[i]==> 'name' ==> obj['name'] ==> 取值成功

obj.arr.[i] 是先取 obj.arr, 再通过obj.arr取[i]:

obj.arr==> undefined ==> undefined[i] ==> 报错
嵌套的由内而外
链式由左往右

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...