简体   繁体   English

Javscript:左括号之前和最后一个括号之后没有双引号

[英]Javscript: No double quote before the opening bracket and after the last bracket

The issue is related to the extra double quotes " character in the products array in between the opening [ and the first { , as well as between the closing } and ] , this comes from the JavaScript variable called "products" being printed as a string. So the question is how to get that variable to print without the surrounding double quotes?该问题与产品数组中开头[和第一个{之间以及结尾}]之间的额外双引号"字符有关,这来自名为“products”的 JavaScript 变量被打印为字符串. 所以问题是如何在没有周围双引号的情况下打印该变量?

let products = '';
        for(var i=0; i<this.items.length; i++) {
            products += "{";
            products += "'name'    : '" + this.items[i].info.brand + " " + this.items[i].info.title + "',";
            products += "'id'    : '" + this.items[i].info.sku + "',";
            products += "'price'    : '" + this.items[i].info.price + "',";
            products += "'brand'    : '" + this.items[i].info.brand + "',";
            products += "'category'    : '" + this.items[i].info.category + "',";
            products += "'variant'    : '" + this.items[i].info.color + "',";
            products += "'quantity'    : '" + this.items[i].quantity + "',";
            products += "}";
            if(i != (this.items.length - 1)){
                products += ',';
            }
            console.log(products);
        }

So when I print the products, you can see the entire products section is within double quotes.所以当我打印产品时,你可以看到整个产品部分都在双引号内。 What I am trying to do is there should be no double quote before the opening bracket of the first product, and after the last bracket of the last product.我想要做的是在第一个产品的左括号之前和最后一个产品的最后一个括号之后不应该有双引号。

在此处输入图像描述

You probably are trying to build an object, in which case you should just use .map on this.items , eg:您可能正在尝试构建一个 object,在这种情况下,您应该只在this.items .map例如:

 function example() { return { products: this.items.map((item) => { return { "name": item.info.brand + " " + item.info.title, "id": item.info.sku, "price": item.info.price, "brand": item.info.brand, "category": item.info.category, "variant": item.info.color, "quantity": item.info.quantity }; })}; } console.log( example.bind({ items: [{info: { brand: "whirlpool", title: "dishwasher", sku: "123", price: "$140", category: "dishwashers", color: "white", quantity: 2}}]})() )

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM