简体   繁体   English

如何检查字符串的字符是否已经是数组的元素?

[英]How can I check if a character of a string is already a element of an array?

With a string, ex: data .使用字符串,例如: data I want to insert all new characters in an array, respecting the example I gave the answer should be:我想在数组中插入所有新字符,尊重我给出的例子,答案应该是:

characters = ["d","a","t"];

I did the following up to now:到目前为止,我做了以下工作:

const balanced = string => {
  var characters = [];
  var characters_Counter = 0;
  
  for (var i = 0; i < string.length; i++) {
    if (string.charAt(i) != characters){
      characters[characters_Counter] = string.charAt(i);
      characters_Counter++;
    }
    
    console.log(characters[i]);
  }
  
};

In the if I want to compare string.charAt(i) with all the elements inside characters[] and if it is a new character do the if 's content.if我想将string.charAt(i)characters[]内的所有元素进行比较,如果它是一个新字符,请执行if的内容。 The problem is: I'm stuck, I can't think a way to make this comparison work.问题是:我被卡住了,我想不出一种方法来进行这种比较。

Use the includes() method to check if an element (character) is inside an array使用includes()方法检查元素(字符)是否在数组内

 const balanced = string => { var characters = []; var characters_Counter = 0; for (var i = 0; i < string.length; i++) { if (!characters.includes(string.charAt(i))) { // <------ here characters[characters_Counter] = string.charAt(i); characters_Counter++; console.log(characters[i]); } } }; balanced("data");

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

相关问题 如何检查字符串中的最后一个字符? - How can I check the last character in a string? 如何检查 javascript 数组是否已包含特定数组 - How can I check if javascript array already contains a specific array 如何检查我的DOM是否已包含ID的元素? - How can i check if my DOM already contains an element by id? 如何检查字符串的第一个字符是否是数字作为 *ngIf 中的条件 - How can I check if the first character of a string it is a number as a condition in *ngIf 如何检查字符串字符是否在 JavaScript 数组中? - How to check if a string character is in a JavaScript array? 我如何检查字符串是否包含数组的元素 - How could i check if a string contains an element of an array 如何在 JS 中将字符串拆分为 2 个字符块的数组? - How can I split a string into an array of 2 character blocks in JS? 如何检查名称是否已在此列表中? - How can I check if a name is already in this list? 我如何使用javascript数组检查字符串匹配的正则表达式是否已经存在 - How do I check if a string matching regex already exists in array with javascript 如何检查字符串中的第一个字符以及如何将该字符串发送到 Jquery 中的数组中? - How to check first character in string and how to send that string into an array in Jquery?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM