收集Javascript案例集
搜索关键字,返回完整路径,返回数组,如
[
[ '北京市', '朝阳区', '建外街道' ],
[ '北京市', '朝阳区', '三里屯街道' ],
[ '北京市', '东城区', '东直门街道' ],
[ '北京市', '东城区', '东华门街道' ],
[ '北京市', '东城区', '东华门街道', '新中街社区' ]
]
尝试一下>>
const data = {
label: "北京市",
children: [{
label: "朝阳区",
children: [{ label: "建外街道" }, { label: "三里屯街道" }],
},
{
label: "东城区",
children: [
{ label: "东直门街道" },
{
label: "东华门街道",
children: [{ label: "胡家园社区" }, { label: "新中街社区" }],
},
],
},
],
};
function seach(keyword) {
var result = [];
function exec(data, parentPath) {
var currentPath = parentPath.concat(data.label);
if (data.label.indexOf(keyword) > -1) { //data.label.indexOf 等于 data.label.search ES有
result.push(currentPath);
}
// if (Reflect.has(data, "children")) { //ES6里才有的
if (typeof data.children === "object" && data.children.length > 0) {
var children = data.children;
children.forEach((item) => {
exec(item, currentPath);
});
}
};
// 执行exec函数,传入data和空数组
exec(data, []);
return result;
}
// 调用seach函数,传入关键字,并打印结果
const res = seach("街");
console.log(res);
document.write(res.join("
"));
`reduce()` 方法是 JavaScript 数组的一个方法,用于对数组中的元素进行累积操作,最后返回一个值。它通常用于求和、求积、求最大值、求最小值等操作。
尝试一下>>
array.reduce(function(accumulator, currentValue) {
// accumulator 是累加器,初始值为第一个元素
// currentValue 是当前元素
// 返回 accumulator 的下一个值
}, initialValue);
其中,accumulator 是累加器,currentValue 是当前元素,initialValue 是累加器的初始值。
const numbers = [1, 2, 3, 4, 5];
const sum = numbers.reduce(function(accumulator, currentValue) {
return accumulator + currentValue;
}, 0);
console.log(sum); // 输出 15
当使用JavaScript进行请求时,可以使用XMLHttpRequest(XHR)对象或fetch API来发送请求。
尝试一下>>
<script>
test1();
test2();
function test1(){
// XMLHttpRequest(XHR)对象
// 创建XMLHttpRequest对象
var xhr = new XMLHttpRequest();
// 设置请求方法和URL
xhr.open('GET', 'http://xiyueta.com/');
// 发送请求
xhr.send();
// 取消请求
xhr.abort();
}
function test2(){
// fetch API
// 创建AbortController对象
var controller = new AbortController();
// 创建AbortSignal对象
var signal = controller.signal;
// 发送请求
fetch('http://xiyueta.com/', { signal })
.then(response => response.json())
.then(data => {
console.log(data);
})
.catch(error => {
if (error.name === 'AbortError') {
console.log('请求已取消');
} else {
console.error('请求发生错误', error);
}
});
// 取消请求
controller.abort();
}
</script>