You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过存储前三段IP的数组匹配用户IP并展示指定提示

实现方案

首先修正你的数组定义语法,JS数组需要用方括号包裹元素:

const internal = ['123.156.189','122.198.44','120.120.120','111.156.40']

核心逻辑是把用户完整IP的前三段提取出来,再和数组内的前缀匹配即可,完整可用代码如下:

// 提取用户IP的前三段:按.分割后取前3段重新拼接
const userIPPrefix = ip.split('.').slice(0, 3).join('.')
// 匹配判断
const showLoading = internal.includes(userIPPrefix)
// 控制元素显示状态
document.getElementById('loading').style.display = showLoading ? 'block' : 'none'

优化方案(更严谨)

如果要避免出现123.156.189匹配到123.156.1891.xx这类误判的情况,可以用Array.prototype.some()方法加前缀校验:

const showLoading = internal.some(prefix => ip.startsWith(`${prefix}.`))
document.getElementById('loading').style.display = showLoading ? 'block' : 'none'

补充说明

你之前写的遍历逻辑是冗余的,includes本身就是数组实例的全局匹配方法,不需要额外写for循环遍历数组,直接调用即可得到全局匹配结果。

内容的提问来源于stack exchange,提问作者here2learn

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.14 11:45:02