【问题标题】:How to make a function to find 0如何编写一个函数来查找 0
【发布时间】:2022-12-07 20:09:24
【问题描述】:

我有一个像这样的数组:

["oh", 2]
["yes", 2]
["sheet", 2]
["really", 1]
["bro", 1]
["om", 0]
["a", 0]
["to", 0]

我需要像数组的第二个含义一样结帐不是 0,我尝试使用类似的功能如果 arr != 0 返回 arr,但当找到值 0 时它也会返回未定义。 如何在没有 0 值数组的情况下使输出像 word - number 一样?

例如我需要输出:oh - 2, yes - 2, sheet - 2, really - 1, bro - 1

【问题讨论】:

  • 这些数组是否包含在一个更大的数组中?你试图解决你自己的问题,你能分享那个(相关的)吗?minimal reproducible example“代码?它出了什么问题,以什么方式报告了任何错误?

标签: javascript


【解决方案1】:

要过滤掉示例中第二个元素值为 0 的数组,可以将 Array.filter() 方法与 Array.join() 方法结合使用。

下面是一个示例,说明如何使用这些方法过滤掉第二个元素值为 0 的数组,并以“word - number”格式创建剩余数组的字符串:

var arr = [  ["oh", 2],
    ["yes", 2],
    ["sheet", 2],
    ["really", 1],
    ["bro", 1],
    ["om", 0],
    ["a", 0],
    ["to", 0]
];

// Filter out the arrays with a value of 0 for the second element
var filteredArr = arr.filter(function(item) {
  return item[1] != 0;
});

// Create a string of the remaining arrays in the format "word - number"
var output = filteredArr.map(function(item) {
   return item[0] + " - " + item[1];
}).join(", ");

console.log(output); // "oh - 2, yes - 2, sheet - 2, really - 1, bro - 1"

在这个例子中,Array.filter() 方法用于过滤掉第二个元素值为 0 的数组。然后使用 Array.map() 方法为每个剩余数组创建格式为“word - number”的新字符串数组,并使用 Array.join() 方法将字符串连接成单个字符串用逗号和空格分隔。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-05-10
    • 1970-01-01
    • 1970-01-01
    • 2023-02-02
    • 2014-11-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多