python 数组 indexof_indexOf() 如何判断一个元素在指定数组中是否存在? 找出指定元素出现的所有位置? indexOf()方法 是正序查找,lastIndexOf()是倒叙查找...

indexOf()方法返回在数组中可以找到一个给定元素的第一个索引,如果不存在,则返回-1。

let a = [2, 9, 7, 8, 9];

a.indexOf(2); // 0

a.indexOf(6); // -1

a.indexOf(7); // 2

a.indexOf(8); // 3

a.indexOf(9); // 1

if (a.indexOf(3) === -1) {

// element doesn't exist in array

}

语法

arr.indexOf(searchElement)

arr.indexOf(searchElement[, fromIndex = 0])

参数

searchElement要查找的元素fromIndex开始查找的位置。如果该索引值大于或等于数组长度,意味着不会在数组里查找,返回-1。如果参数中提供的索引值是一个负值,则将其作为数组末尾的一个抵消,即-1表示从最后一个元素开始查找,-2表示从倒数第二个元素开始查找 ,以此类推。 注意:如果参数中提供的索引值是一个负值,仍然从前向后查询数组。如果抵消后的索引值仍小于0,则整个数组都将会被查询。其默认值为0.

返回值

首个被找到的元素在数组中的索引位置; 若没有找到则返回 -1

描述

indexOf 使用strict equality (无论是 ===, 还是 triple-equals操作符都基于同样的方法)进行判断 searchElement与数组中包含的元素之间的关系。

应用:使用indexOf方法确定多个值在数组中的位置。

1 var array = [2, 5, 9];2 array.indexOf(2); //0

3 array.indexOf(7); //-1

4 array.indexOf(9, 2); //2

5 array.indexOf(2, -1); //-1

6 array.indexOf(2, -3); //0

应用:找出指定元素出现的所有位置

1 var indices =[];2 var array = ['a', 'b', 'a', 'c', 'a', 'd'];3 var element = 'a';4 var idx =array.indexOf(element);5 while (idx != -1) {6 indices.push(idx);7 idx = array.indexOf(element, idx + 1);8 }9 console.log(indices);10 //[0, 2, 4]

应用:判断一个元素是否在数组里,不在则更新数组

1 functionupdateVegetablesCollection (veggies, veggie) {2 if (veggies.indexOf(veggie) === -1) {3 veggies.push(veggie);4 console.log('New veggies collection is : ' +veggies);5 } else if (veggies.indexOf(veggie) > -1) {6 console.log(veggie + ' already exists in the veggies collection.');7 }8 }9

10 var veggies = ['potato', 'tomato', 'chillies', 'green-pepper'];11

12 //New veggies collection is : potato,tomato,chillies,green-papper,spinach

13 updateVegetablesCollection(veggies, 'spinach');14 //spinach already exists in the veggies collection.

15 updateVegetablesCollection(veggies, 'spinach');

Polyfill

indexOf 在ECMA-262 标准 的第5版中被加入,但并非所有的浏览器都支持该方法。你可以在编写scripts时,在其开头使用以下代码,它能够允许你在没有本地支持的情况下使用indexOf方法。该算法符合ECMA-262第5版其中一项规定, 即假定 TypeError和 Math.abs 呈现它们原有的价值。

1 //Production steps of ECMA-262, Edition 5, 15.4.4.14

2 //Reference: http://es5.github.io/#x15.4.4.14

3 if (!Array.prototype.indexOf) {4 Array.prototype.indexOf = function(searchElement, fromIndex) {5

6 vark;7

8 //1. Let O be the result of calling ToObject passing

9 //the this value as the argument.

10 if (this == null) {11 throw new TypeError('"this" is null or not defined');12 }13

14 var O = Object(this);15

16 //2. Let lenValue be the result of calling the Get

17 //internal method of O with the argument "length".

18 //3. Let len be ToUint32(lenValue).

19 var len = O.length >>> 0;20

21 //4. If len is 0, return -1.

22 if (len === 0) {23 return -1;24 }25

26 //5. If argument fromIndex was passed let n be

27 //ToInteger(fromIndex); else let n be 0.

28 var n = +fromIndex || 0;29

30 if (Math.abs(n) ===Infinity) {31 n = 0;32 }33

34 //6. If n >= len, return -1.

35 if (n >=len) {36 return -1;37 }38

39 //7. If n >= 0, then Let k be n.

40 //8. Else, n<0, Let k be len - abs(n).

41 //If k is less than 0, then let k be 0.

42 k = Math.max(n >= 0 ? n : len - Math.abs(n), 0);43

44 //9. Repeat, while k < len

45 while (k

47 //This is implicit for LHS operands of the in operator

48 //b. Let kPresent be the result of calling the

49 //HasProperty internal method of O with argument Pk.

50 //This step can be combined with c

51 //c. If kPresent is true, then

52 //i. Let elementK be the result of calling the Get

53 //internal method of O with the argument ToString(k).

54 //ii. Let same be the result of applying the

55 //Strict Equality Comparison Algorithm to

56 //searchElement and elementK.

57 //iii. If same is true, return k.

58 if (k in O && O[k] ===searchElement) {59 returnk;60 }61 k++;62 }63 return -1;64 };65 }

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 以下是可以实现上述需求的Python代码: ```python array = [3, 1, 5, 7, 2, 4] min1 = min(array) array.remove(min1) # 移除最小值 min2 = min(array) array.remove(min2) # 移除次小值 new_num = min1 + min2 array.append(new_num) # 将相加的结果添加到原数组末尾 print(array) ``` 首先,获取原数组中的最小值min1,并将它从数组中移除。接着,再获取次小值min2,并将它从数组中移除。然后,计算min1和min2的和new_num,将它添加到原数组末尾。最后,输出新的数组。 ### 回答2: 你可以使用以下的代码来实现将数组中最小的两个值相加并存到该数组中,形成一个新的数组: ```python def add_smallest_values(arr): # 找出最小的两个值 smallest_values = sorted(arr)[:2] # 计算最小值的和 sum_of_smallest = sum(smallest_values) # 将和添加到原始数组中,并形成一个新的数组 arr.append(sum_of_smallest) return arr # 示例使用 original_array = [5, 2, 8, 1, 9] new_array = add_smallest_values(original_array) print(new_array) ``` 输出结果将会是`[5, 2, 8, 1, 9, 3]`,其中3是最小的两个值1和2的和。 ### 回答3: 可以先找到数组中的最小值和次小值,然后将它们相加得到结果,最后将结果添加到数组中形成一个新的数组。 以下是一个简单的示例代码: ```python def add_smallest_two(arr): # 找到数组中最小的两个值的索引 smallest_index = 0 second_smallest_index = 1 if arr[1] < arr[0]: smallest_index = 1 second_smallest_index = 0 for i in range(2, len(arr)): if arr[i] < arr[smallest_index]: second_smallest_index = smallest_index smallest_index = i elif arr[i] < arr[second_smallest_index]: second_smallest_index = i # 计算最小的两个值的和 smallest_sum = arr[smallest_index] + arr[second_smallest_index] # 将结果添加到数组中 new_arr = arr.copy() # 创建一个新的数组,以免修改原来的数组 new_arr.append(smallest_sum) return new_arr # 测试 nums = [5, 8, 3, 10, 2] new_nums = add_smallest_two(nums) print(new_nums) ``` 运行以上代码,将输出 `[5, 8, 3, 10, 2, 5]`。其中,最小的两个值是2和3,它们的和是5,将它添加到数组末尾形成新的数组

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值