Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/416.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 两种类型的for循环-为什么只有一种有效?_Javascript_For Loop - Fatal编程技术网

Javascript 两种类型的for循环-为什么只有一种有效?

Javascript 两种类型的for循环-为什么只有一种有效?,javascript,for-loop,Javascript,For Loop,我有以下Javascript代码: var controller = { initApp: function(){ var getCartData = $.ajax({ url: '/cart' }), getCategoryData = $.ajax({ url: '/categories' }), getSupplierData = $.ajax({ url: '/suppliers'}), getProdcuts = $.ajax({

我有以下Javascript代码:

var controller = {
initApp: function(){
    var getCartData = $.ajax({ url: '/cart' }),
        getCategoryData = $.ajax({ url: '/categories' }),
        getSupplierData = $.ajax({ url: '/suppliers'}),
        getProdcuts = $.ajax({url: '/products'});

    // Main controller logic starts when all data are loaded in
    $.when(getCartData, getCategoryData, getSupplierData, getProdcuts
    ).done( function( cart, categories, suppliers, products ) {
        var model = new Model(cart, categories, suppliers, JSON.parse(products[0]));

        console.log(model.products);
        console.log(typeof model.products);

        for(var i = 0; i<model.products.length; i++){
            console.log(model.products[i]);
        }

        for(product in model.products){
            console.log(product);
        }

    });
}
var控制器={
initApp:function(){
var getCartData=$.ajax({url:'/cart'}),
getCategoryData=$.ajax({url:'/categories'}),
getSupplierData=$.ajax({url:'/suppliers'}),
getProdcuts=$.ajax({url:'/products'});
//当所有数据加载时,主控制器逻辑启动
$.when(getCartData、getCategoryData、getSupplierData、getProdcuts
).完成(功能(购物车、类别、供应商、产品){
var model=新模型(购物车、类别、供应商、JSON.parse(产品[0]);
控制台.日志(型号.产品);
控制台.日志(型号.产品的类型);
对于(var i=0;iProdukt)来说,也是一个关键:

a={a:1,b:2}
for(key in a){
 alert(key);// a.   B.  
}
所以你需要做:

for(product in model.products){ 
 console.log(model[product]);
 }
但是您应该使用普通for循环。为什么?因为原型也是用键处理的:

Array.prototype.test=2;

使用之前执行过的代码运行booth循环。因为在中也会回显2,您不想要的…

可能您想使用
For…of
而不是
For…in
读取您正在迭代的是属性而不是值。然后读取