【发布时间】:2010-08-02 19:06:30
【问题描述】:
标题总结了它。
【问题讨论】:
标题总结了它。
【问题讨论】:
如果有人想要使用jquery 的更集成的方法:
(function($){
$.extend({
// Case insensative $.inArray (http://api.jquery.com/jquery.inarray/)
// $.inArrayIn(value, array [, fromIndex])
// value (type: String)
// The value to search for
// array (type: Array)
// An array through which to search.
// fromIndex (type: Number)
// The index of the array at which to begin the search.
// The default is 0, which will search the whole array.
inArrayIn: function(elem, arr, i){
// not looking for a string anyways, use default method
if (typeof elem !== 'string'){
return $.inArray.apply(this, arguments);
}
// confirm array is populated
if (arr){
var len = arr.length;
i = i ? (i < 0 ? Math.max(0, len + i) : i) : 0;
elem = elem.toLowerCase();
for (; i < len; i++){
if (i in arr && arr[i].toLowerCase() == elem){
return i;
}
}
}
// stick with inArray/indexOf and return -1 on no match
return -1;
}
});
})(jQuery);
【讨论】:
$.extend({ inArrayIn: function ... 而不仅仅是$.inArrayIn = function ...?
你可以使用each()...
// Iterate over an array of strings, select the first elements that
// equalsIgnoreCase the 'matchString' value
var matchString = "MATCHME".toLowerCase();
var rslt = null;
$.each(['foo', 'bar', 'matchme'], function(index, value) {
if (rslt == null && value.toLowerCase() === matchString) {
rslt = index;
return false;
}
});
【讨论】:
matchString.toLowerCase()值存储在变量中而不是为每次迭代计算它不是更有效吗?
equals 是 JavaScript 中的原生方法?我觉得应该是===吧?
感谢@Drew Wills。
我改写成这样:
function inArrayCaseInsensitive(needle, haystackArray){
//Iterates over an array of items to return the index of the first item that matches the provided val ('needle') in a case-insensitive way. Returns -1 if no match found.
var defaultResult = -1;
var result = defaultResult;
$.each(haystackArray, function(index, value) {
if (result == defaultResult && value.toLowerCase() == needle.toLowerCase()) {
result = index;
}
});
return result;
}
【讨论】:
没有。您将不得不摆弄您的数据,我通常将所有字符串都设为小写以便于比较。还有可能使用自定义比较函数,该函数会进行必要的转换以使比较不区分大小写。
【讨论】:
可以循环遍历数组并toLower每个元素并toLower您要查找的内容,但是在那个时候,您最好只比较它而不是使用inArray()
【讨论】:
这些天我更喜欢使用underscore 来完成这样的任务:
a = ["Foo","Foo","Bar","Foo"];
var caseInsensitiveStringInArray = function(arr, val) {
return _.contains(_.map(arr,function(v){
return v.toLowerCase();
}) , val.toLowerCase());
}
caseInsensitiveStringInArray(a, "BAR"); // true
【讨论】:
看起来您可能必须为此实施自己的解决方案。 Here 是一篇关于向 jQuery 添加自定义函数的好文章。您只需要编写一个自定义函数来循环和规范化数据然后进行比较。
【讨论】:
这种方式对我有用..
var sColumnName = "Some case sensitive Text"
if ($.inArray(sColumnName.toUpperCase(), getFixedDeTasksColumns().map((e) =>
e.toUpperCase())) == -1) {// do something}
【讨论】: