原生JS实现 some() 方法

定义和用法

some() 方法用于检测数组中的元素是否满足指定条件(函数提供)。

some() 方法会依次执行数组的每个元素:

  • 如果有一个元素满足条件,则表达式返回true , 剩余的元素不会再执行检测。
  • 如果没有满足条件的元素,则返回false。

注意: some() 不会对空数组进行检测。

注意: some() 不会改变原始数组。

语法

array.some(function(currentValue,index,arr),thisValue)

参数说明

参数描述
function(currentValue, index,arr)必须。函数,数组中的每个元素都会执行这个函数
函数参数:
参数描述
currentValue必须。当前元素的值
index可选。当前元素的索引值
arr可选。当前元素属于的数组对象
thisValue可选。对象作为该执行回调时使用,传递给函数,用作 "this" 的值。
如果省略了 thisValue ,"this" 的值为 "undefined"

实现

// 实现some
Array.prototype.some = function(fn, value){
    if (typeof fn !== "function") {
        return false;
    }
    var arr = this;
    for (var i = 0; i < arr.length; i++) {
        var result = fn.call(value, arr[i], i, arr);
        if (result) return true;
    }
    return false;
}

测试

var arr3 = [2,23,4,2,4,2,2];
console.log(arr3.some(function(item, index, arr){
    return item >= 6;
}));

好的,我可以为您提供一个简单的例子: HTML: ```html <div class="tab"> <button class="tablinks" onclick="openTab(event, 'tab1')">Tab 1</button> <button class="tablinks" onclick="openTab(event, 'tab2')">Tab 2</button> <button class="tablinks" onclick="openTab(event, 'tab3')">Tab 3</button> </div> <div id="tab1" class="tabcontent"> <h3>Tab 1 Content</h3> <p>Some text...</p> </div> <div id="tab2" class="tabcontent"> <h3>Tab 2 Content</h3> <p>Some text...</p> </div> <div id="tab3" class="tabcontent"> <h3>Tab 3 Content</h3> <p>Some text...</p> </div> ``` CSS: ```css /* 隐藏所有tab内容 */ .tabcontent { display: none; } /* 标签页按钮样式 */ .tab button { background-color: #eee; border: none; color: black; padding: 10px 20px; cursor: pointer; } /* 激活的标签页按钮样式 */ .tab button.active { background-color: #ccc; } /* 标签页内容样式 */ .tabcontent { padding: 20px; border: 1px solid #ccc; } /* 第一个标签页默认显示 */ #tab1 { display: block; } ``` JavaScript: ```javascript function openTab(event, tabName) { // 获取所有的 tab 内容 var tabcontent = document.getElementsByClassName("tabcontent"); // 隐藏所有的 tab 内容 for (var i = 0; i < tabcontent.length; i++) { tabcontent[i].style.display = "none"; } // 获取所有的 tab 按钮 var tablinks = document.getElementsByClassName("tablinks"); // 将所有的 tab 按钮样式设置为非激活状态 for (var i = 0; i < tablinks.length; i++) { tablinks[i].className = tablinks[i].className.replace(" active", ""); } // 显示当前选中的 tab 内容 document.getElementById(tabName).style.display = "block"; // 设置当前选中的 tab 按钮为激活状态 event.currentTarget.className += " active"; } ``` 当用户点击任意一个标签页按钮时,`openTab`函数会被调用,隐藏所有标签页内容,将当前标签页内容设置为显示状态,同时将当前标签页按钮样式设置为激活状态。
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值