Javascript 从多个字符串中只保留一个字符串-数组
我只需要从数组中保留一个字符串:Javascript 从多个字符串中只保留一个字符串-数组,javascript,html,arrays,Javascript,Html,Arrays,我只需要从数组中保留一个字符串: var string = "dog"; var array = ["dog","cat","bird","snake","tiger","dog", "dog", "cat"]; 好吧,这看起来很愚蠢,为什么我写了多次“狗”,但这只是一个例子 实际上,它将从输入标记生成一个数组。像这样: firstEntry = true; inputValue = inputfield.value; if(inputValue != ''){
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.
我在这里或谷歌上没有找到任何东西。不知道你的意思。如果需要只包含初始数组中的“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"]
不使用过滤器
,这是一种从数组中删除双值的通用方法:
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
方法,请参阅。链接页面还包含一个垫片,用于在旧浏览器中启用该方法。您可以使用自定义函数;如果在筛选之前找到特定值,则从那时起:
var string = "dog";
var array = ["dog","cat","bird","snake","tiger","dog", "dog", "cat"];
var result = (function() {
var found = false;
// @see: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
return array.filter(function(value) {
if (value == string) {
// only allow this one time
return found ? false : found = true;
}
return true;
});
}());
我想如果我有:
array = ["dog","cat","bird","snake","tiger","dog", "dog", "cat"]
我希望我能:
array = ["dog","cat","bird","snake","tiger"]
感谢您的noDouble-功能
这是我所需要的完美方式。不清楚你想要实现什么。你只是想过滤掉数组,这样就只剩下你要查找的单个值了吗?我在这里或Google中没有找到任何东西如果我理解正确,请尝试重新表述问题,以更清楚地说明您在寻找什么。基本上,如果某个特定值出现N次,您希望最多保留一次?
array = ["dog","cat","bird","snake","tiger"]