本篇搭配 LeetCode 1.Two Sum
Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.
Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Explanation: Because nums[0] + nums[1] == 9, we return [0, 1].
Input: nums = [3,2,4], target = 6
Output: [1,2]
Input: nums = [3,3], target = 6
Output: [0,1]
Array.indexOf('keyword')
检查阵列里的元素索引值。
输出:索引值
(元素的位置0/1/2...),找不到结果回传-1
var twoSum = function(nums, target) {
for (let i = 0 ; i < nums.length ; i++) {
const secondNum = target - nums[i];
if (nums.indexOf(secondNum) > -1){
return [i , nums.indexOf(secondNum)];
} else{
i++
}
}
};
Array.includes('keyword')
检查阵列里是否包含元素。
输出:布林值
,找得到回传true
;找不到则回传false
var twoSum = function(nums, target) {
for (let i = 0 ; i < nums.length ; i++) {
const secondNum = target - nums[i];
if (nums.includes(secondNum)){
return [i , nums.indexOf(secondNum)];
} else{
i++
}
}
};
使用箭头函示检查阵列中每个内容是否符合条件。
输出:第一个符合条件的值;否则返回undefined
。
let age = [21, 43, 23, 1, 34, 12, 8];
console.log(age.find(i => i > 20));
console.log(age.find(i => i > 21))
// output
21
43
如同 find(),使用箭头函示检查阵列中每个内容是否符合条件。
输出:阵列,包含符合条件的所有值;否则返回空阵列[]
let age = [21, 43, 23, 1, 34, 12, 8];
console.log(age.filter(i => i > 20));
console.log(age.filter(i => i > 21));
// output
[21, 43, 23, 34]
[43, 23, 34]
参考来源:
https://www.delftstack.com/zh-tw/howto/javascript/javascript-array-contains/
>>: 【Lua】用 Fengari 让 Lua 取代 JavaScript 吧!
各位参赛选手~我是今天的主播 小笠宏树!各位准备好了!!!3 2 1 ~ 比赛开始! 今天来推脑洞神...
#前言 昨天我们稍微介绍实际案例是什麽样子,挑战终於进到了尾声,今天我们来介绍一些重要的工具! 00...
Logstash Part II 本篇介绍如何搭配filebeat和logstash,把apache...
今天我们用一个实例来分析,如何从视觉化报表中看出隐藏在日志中我们想查看的讯息。接下来使用的范例资料都...
GCE 如何在GCP上建立,如同以往机房建立Server的实体VM,在GCP上提供了三种方式,其中最...