簡體   English   中英

如何增加 obj 鍵?

[英]How to increment the obj key?

我試圖在字符串中找到相同的數字,但 obj 鍵不想增加值,它仍然被讀取為否定

function yOrN(phone) {
  const temp = [];
  for (let i = 0; i < phone.length; i++) {
    const el = String(phone[i]);
    if (el.length > 10) {
      temp.push("No");
      break;
    }
    let tempObj = {};
    for (let j = 0; j < el.length; j++) {
      const em = el[j];
      if (!tempObj[el[j]]) {
        tempObj[el[j]] = 0;           //! this side make me stucked rn
      } else if (tempObj) {
        tempObj[el[j]] = tempObj[el[j]] + 1;
      }
    }
    for (const num in tempObj) {
      if (tempObj[num] < 3 || tempObj[num] > 4) {
        temp.push("No");
        break;
      } else {
        temp.push("Yes");
        break;
      }
    }
  }
  return temp;
}
console.log(yOrN([98887432, 12345890]));

預期的輸出是 ["yes", "no"]:( 而它仍然是 ["no", "no"]

{ '2': 1, '3': 1, '4': 1, '7': 1, '8': 5, '9': 1 } for the index 0
{ '0': 1, '1': 1, '2': 1, '3': 1, '4': 1, '5': 1, '8': 1, '9': 1 } for the index 1

在任何情況下,您的 fi=unction 都無法使用您的實際參數值返回Yes

我認為您正在尋找Object.values()

 console.log( yOrN( [98887432, 12345890]) ); function yOrN(phone) { const temp = []; for (let el of phone.map(String)) { let res = 'Yes'; if (el.length > 10) res = 'No'; else { let tempObj = [...el].reduce((a,c)=> ( a[c]??= 0, a[c]++, a), {}) if ( Object.values(tempObj).some( v => v < 3 || v > 4)) res = 'No'; console.log( res, JSON.stringify( tempObj )) } temp.push(res); } return temp; }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM