首页 > 解决方案 > 将项目添加到数组中 - 单独

问题描述

目标:单击一个按钮并将成分作为单独的项目添加到数组中。

当前设置:

    <% currentUser.ingredients.forEach(function(items){ %> 
   <p class='ingredients'>  <%= items %> </p>
    <% }) %>

这给出了:蓝莓芒果柠檬汁

然后,我希望能够通过单击按钮将成分作为单独的项目添加到数组中:

var allIngredients = []

$("#makeList").click(function() {

allIngredients.push($(".ingredients").text())
console.log(allIngredients)

}); 

这打印 [“Blueberrys Mango Lemon Juice”]

问题是它是一个项目而不是单独的项目。

我需要更改什么以使它们成为单独的项目?

标签: javascriptarraysloopsejs

解决方案


你需要迭代$('.ingredients')

var allIngredients = [];

$("#makeList").click(function() {

    $(".ingredients").each(function() {
        allIngredients.push($(this).text());
    });

    console.log(allIngredients);

}); 

推荐阅读