我有一系列数字,我需要确保它们是唯一的.我在互联网上找到了下面的代码片段,它的工作情况很好,直到数组中的数字为零.我发现这个其他脚本在SO上看起来几乎就像它,但它不会失败.
所以为了帮助我学习,有人可以帮我确定原型脚本出错的地方吗?
Array.prototype.getUnique = function() {
var o = {}, a = [], i, e;
for (i = 0; e = this[i]; i++) {o[e] = 1};
for (e in o) {a.push (e)};
return a;
}
Run Code Online (Sandbox Code Playgroud)
如果您已经使用过任何长度的JavaScript,那么您就知道Internet Explorer没有为Array.prototype.indexOf()[包括Internet Explorer 8]实现ECMAScript函数.这不是一个大问题,因为您可以使用以下代码扩展页面上的功能.
Array.prototype.indexOf = function(obj, start) {
for (var i = (start || 0), j = this.length; i < j; i++) {
if (this[i] === obj) { return i; }
}
return -1;
}
Run Code Online (Sandbox Code Playgroud)
我什么时候应该实现这个?
我应该使用以下检查将其包装在我的所有页面上,检查是否存在原型函数,如果不存在,请继续并扩展Array原型?
if (!Array.prototype.indexOf) {
// Implement function here
}
Run Code Online (Sandbox Code Playgroud)
或者浏览器检查,如果它是Internet Explorer,那么只需实现它?
//Pseudo-code
if (browser == IE Style Browser) {
// Implement function here
}
Run Code Online (Sandbox Code Playgroud) javascript internet-explorer cross-browser internet-explorer-8
有没有办法获得某个属性的所有唯一值.
例如
<div class="bob" data-xyz="fish"></div>
<div class="bob" data-xyz="dog"></div>
<div class="bob" data-xyz="fish"></div>
<div class="bob" data-xyz="cat"></div>
<div class="bob" data-xyz="fish"></div>
Run Code Online (Sandbox Code Playgroud)
我需要在div.bob上获取data-xyz属性的所有不同值,
所以它应该返回鱼,狗和猫.