gpt4 book ai didi

javascript - 从多个字符串中仅保留一个字符串 - 数组

转载 作者:行者123 更新时间:2023-11-28 01:10:46 25 4
gpt4 key购买 nike

我只需要从数组中保留一个字符串:

var string = "dog";

var array = ["dog","cat","bird","snake","tiger","dog", "dog", "cat"];

好吧,为什么我多次写“狗”,这看起来很愚蠢,但这只是一个例子。

实际上,它会根据输入标签创建一个数组。像这样:

  firstEntry = true;

inputValue = inputfield.value;

if(inputValue != ''){
if(firstEntry){
inputArray.push(inputValue);
firstEntry = false;
}

//And know it should leave only one String

inputValueSplit = inputValue.split(/ /g);
removeFromArray(inputValueSplit,'');//This is a external function, (deletes empty Strings)
inputArray = inputValueSplit;


inputArray.filter(inputValue); // Here it should leave only one
// String of multiple Strings from
// same value.

我在此处或 Google 中没有找到任何内容..

最佳答案

不知道你的意思。如果您需要一个仅包含初始数组中“dog”值的数组,则可以使用 Array.filter:

var dogs = ["dog","cat","bird","snake","tiger","dog", "dog", "cat"]
.filter( function(a){ return a == this; }, 'dog' );
//=> ['dog','dog','dog']

如果您想从初始数组中删除双“dog”值:

var singleout = 'dog'
,dogs = (["dog","cat","bird","snake","tiger","dog", "dog", "cat"]
.filter( function(a){ return a != this }, singleout ));
// now dogs contains no 'dog' value, so add 'dog' to it again
dogs.push(singleout);
//=> ["cat", "bird", "snake", "tiger", "cat", "dog"]

不使用过滤器,这是从数组中删除 double 值的通用方法:

function noDoubles(arr) {
var doubleChk = {}, noDoubles = [];
for (var i=0;i<arr.length;i+=1) { doubleChk[arr[i]] = true; }
for (var l in doubleChk) { noDoubles.push(l); }
return noDoubles;
}
noDoubles(["dog","cat","bird","snake","tiger","dog", "dog", "cat"]);
//=> ["dog", "cat", "bird", "snake", "tiger"]

最后,从前面的函数中学习并使用 Array.filter 后,从 Array 中删除 double 可以非常简单:

function noDoubles(arr) {
return arr.filter(function(val) {
return !this[val] ? ((this[val] = true), true) : false;
}, {} );
}
noDoubles(["dog","cat","bird","snake","tiger","dog", "dog", "cat"]);
//=> ["dog", "cat", "bird", "snake", "tiger"]

参见MDN对于 Array.filter 方法。链接的页面还包含一个填充程序,可以在旧版浏览器中启用该方法。

关于javascript - 从多个字符串中仅保留一个字符串 - 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24476455/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com