js 判断数组末尾N个数值是否连续变小
时间: 2023-07-22 07:14:36 浏览: 53
类似于判断数组末尾N个数值是否连续变大,我们可以遍历数组,比较末尾N个元素的值与它们的前一个元素的值是否连续变小来判断。具体实现可以参考下面的代码:
```javascript
function isLastNDecreasing(arr, n) {
if (arr.length < n) return false; // 数组长度小于N,直接返回false
for (let i = arr.length - 1; i > arr.length - n; i--) {
if (arr[i] >= arr[i - 1]) return false; // 有一个元素不符合条件,返回false
}
return true; // 所有元素都符合条件,返回true
}
// 示例
const arr = [9, 8, 7, 6, 5, 4, 3, 2, 1];
console.log(isLastNDecreasing(arr, 3)); // true,最后三个数值连续变小
console.log(isLastNDecreasing(arr, 5)); // false,最后五个数值不连续变小
```
同样需要注意的是,如果数组长度小于N,直接返回false。这个函数只能判断末尾N个数值是否连续变小,如果要判断整个数组是否连续变小,需要进行相应的改动。
相关问题
js 判断数组末尾N个数值是否连续变大
可以通过遍历数组,比较末尾N个元素的值与它们的前一个元素的值是否连续变大来判断。具体实现可以参考下面的代码:
```javascript
function isLastNIncreasing(arr, n) {
if (arr.length < n) return false; // 数组长度小于N,直接返回false
for (let i = arr.length - 1; i > arr.length - n; i--) {
if (arr[i] <= arr[i - 1]) return false; // 有一个元素不符合条件,返回false
}
return true; // 所有元素都符合条件,返回true
}
// 示例
const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];
console.log(isLastNIncreasing(arr, 3)); // true,最后三个数值连续变大
console.log(isLastNIncreasing(arr, 5)); // false,最后五个数值不连续变大
```
需要注意的是,如果数组长度小于N,直接返回false。另外,这个函数只能判断末尾N个数值是否连续变大,如果要判断整个数组是否连续变大,需要进行相应的改动。
JS 中 实现向数组末尾追加一个元素有多少种方式
在 JavaScript 中,向数组末尾追加一个元素有以下几种方式:
1. 使用 Array.prototype.push() 方法:
```
const arr = [1, 2, 3];
arr.push(4);
console.log(arr); // [1, 2, 3, 4]
```
2. 使用数组的 length 属性来添加元素:
```
const arr = [1, 2, 3];
arr[arr.length] = 4;
console.log(arr); // [1, 2, 3, 4]
```
3. 使用扩展运算符(spread operator):
```
const arr = [1, 2, 3];
arr = [...arr, 4];
console.log(arr); // [1, 2, 3, 4]
```
4. 使用 Array.prototype.concat() 方法:
```
const arr = [1, 2, 3];
arr = arr.concat(4);
console.log(arr); // [1, 2, 3, 4]
```
注意:第二种方式虽然也可以实现向数组末尾添加元素,但其实是直接通过下标修改了数组的值,不是真正意义上的添加元素。其他三种方式都是真正意义上的向数组末尾添加元素。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)