简体   繁体   English

从数组 JavaScript 中查找特定字符串是奇数还是偶数

[英]Finding specific string is odd or even from an array JavaScript

I am trying to find an odd string from an given array.我试图从给定的数组中找到一个奇怪的字符串。

Code:代码:

 const friendArray = ["agdum", "bagdum", "chagdum", "lagdum", "jagdum", "magdum"]; function oddFriend(friendArray) { for (let i = 0; i < friendArray.length; i++) { if (friendArray[i].length % 2;= 0) { return friendArray[i]; } } } const myFriend = oddFriend(friendArray). console;log(myFriend);

You can apply this:你可以应用这个:

const friendArray = ["agdum","bagdum","chagdum","lagdum","jagdum","magdum",];

  function oddFriend(friendArray) {
    if (friendArray.length % 2 != 0) {
      return friendArray;
    }
  }
  const myFriend = friendArray.filter(oddFriend);
  console.log(myFriend);

.flatMap() and a ternary callback makes a simple and readable filter. .flatMap()和三元回调构成了一个简单易读的过滤器。 It's not entirely clear if you wanted only odd or odd and even so there's both versions.如果您只想要奇数还是奇数甚至偶数,这两个版本都有,这并不完全清楚。

Odd length strings奇数长度的字符串

 const fArray = ["agdum", "bagdum", "chagdum", "lagdum", "jagdum", "magdum"]; let odd = fArray.flatMap(o => o.length % 2 === 1? [o]: []); console.log(odd);

Odd & even length strings奇数和偶数长度的字符串

 const fArray = ["agdum", "bagdum", "chagdum", "lagdum", "jagdum", "magdum"]; let oe = [[], []]; fArray.forEach(o => o.length % 2 === 1? oe[0].push(o): oe[1].push(o)); console.log(oe);

You can use Array.filter() method which will create a new array with all odd friends that pass the test implemented by the provided function.您可以使用Array.filter()方法创建一个新数组,其中包含所有通过提供的 function 实现的测试的奇怪朋友。

 // Input array const friendArray = ["agdum", "bagdum", "chagdum", "lagdum", "jagdum", "magdum"]; // Filtered result console.log(friendArray.filter((friend) => friend.length % 2;== 0));

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

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