1

我正在 jQuery.com 上做一些 jQuery 教程,现在尝试理解扩展方法。它几乎可以工作。

var object1 = {
                apple: 0,
                banana: {weight: 52, price: 100},
                cherry: 97
                };

            var object2 = {
                banana: {price: 200},
                durian: 100
                };

            var obj =   $.extend(object1, object2);

            for(var key in obj) {
                alert('key: ' + key + '\n' + 'value: ' + obj[key]);

警报框提供以下输出:

  • 键:苹果值:0
  • 键:香蕉值:[对象对象]
  • 关键:樱桃价值:97
  • 关键:榴莲价值:100

第二个键值对应该是banana:200。有人可以解释为什么不是吗?提前致谢。

4

5 回答 5

1

bannana 是一种对象属性。因此,如果您扩展它,它将被秒替换。但是如果你想更新priceandweight属性,你必须像这样编写代码

var obj = $.extend(true, object1, object2);
于 2013-03-24T10:10:33.937 回答
0

The object Banana will be:

banana : {
  weight: 52,
  price: 200
}

$.extend will not remove the keys that are not overwritten, it's cleverer than that. So weight still exists.

The reason it shows [object object] is because there is no toString() method and alert doesn't know how to Stringify the banana Object. If you print the values on their own to the console this is what you will see.

于 2013-03-24T10:02:46.370 回答
0

The alert box simply doesn't show nested objects.

//Use this on your object before you alert
alert(JSON.stringify(myObj));

If you use Chrome or Firebug, you can easily see this output using console.log(myObj) instead of alert. You would need to see the console by pressing Ctrl+Shift+J in Windows.

Hope this helps!

于 2013-03-24T10:04:52.380 回答
0

它向您展示了对象,因为它是对象并且不会深入。

您可以通过添加以下内容轻松测试它:

object2.banana.toString=function (){ return this["price"]; //only for object2's banana. just for demonstrating.

完整代码:http: //jsbin.com/esobuc/2/edit

var object1 = {
                apple: 0,
                banana: {weight: 52, price: 100},
                cherry: 97
                };

            var object2 = {
                banana: {price: 200},
                durian: 100
                };

object2.banana.toString=function (){ return this["price"]; 
}

            var obj =   $.extend(object1, object2);

            for(var key in obj) {
              alert('key: ' + key + '\n' + 'value: ' + obj[key]);}
于 2013-03-24T10:07:12.193 回答
0

以下应该有帮助:

// override banana with its price
object2.banana = object2.banana.price

// merge both objects
var obj = $.extend(object1, object2);
于 2013-03-24T10:16:16.967 回答