【JavaScript】01数组原型对象的最后一个元素、计数器

题目一:数组原型对象的最后一个元素

请你编写一段代码实现一个数组方法,使任何数组都可以调用 array.last() 方法,这个方法将返回数组最后一个元素。如果数组中没有元素,则返回 -1

你可以假设数组是 JSON.parse 的输出结果。

示例 1 :

复制代码
输入:nums = [null, {}, 3]
输出:3
解释:调用 nums.last() 后返回最后一个元素: 3。

示例 2 :

复制代码
输入:nums = []
输出:-1
解释:因为此数组没有元素,所以应该返回 -1。
提示:
  • arr 是一个有效的 JSON 数组

  • 0 <= arr.length <= 1000

    /**

    • @return {null|boolean|number|string|Array|Object}
      */
      Array.prototype.last = function() {

    };

    /**

    • const arr = [1, 2, 3];
    • arr.last(); // 3
      */

解题:

方法一:

复制代码
Array.prototype.last = function() {
    if(this.length===0){
        return -1;
    }else{
       return this[this.length-1] 
    }
    
};

方法二:

复制代码
Array.prototype.last = function() {
  return this.length === 0 ? -1 : this[this.length - 1];
}

作者:力扣官方题解
链接:https://leetcode.cn/problems/array-prototype-last/solutions/2506895/shu-zu-yuan-xing-dui-xiang-de-zui-hou-yi-4phe/
来源:力扣(LeetCode)

题目二:计数器

给定一个整型参数 n,请你编写并返回一个 counter函数。这个 counter函数最初返回 n,每次调用它时会返回前一个值加 1 的值 ( n , n + 1 , n + 2 ,等等)。

示例 1:

复制代码
输入:
n = 10 
["call","call","call"]
输出:[10,11,12]
解释:
counter() = 10 // 第一次调用 counter(),返回 n。
counter() = 11 // 返回上次调用的值加 1。
counter() = 12 // 返回上次调用的值加 1。

示例 2:

复制代码
输入:
n = -2
["call","call","call","call","call"]
输出:[-2,-1,0,1,2]
解释:counter() 最初返回 -2。然后在每个后续调用后增加 1。

提示:

  • -1000 <= n <= 1000
  • 0 <= calls.length <= 1000
  • calls[i] === "call"

解题:

方法一:

复制代码
function createCounter(n) {  
    let count = n; // 初始化计数值为 n  
    return function() {  
        return count++; // 返回当前计数值,并同时将其递增  
    };  
} 

方法二:

复制代码
var createCounter = function(n) {
  return function() {
    return n++;      
  };
};

作者:力扣官方题解
链接:https://leetcode.cn/problems/counter/solutions/2487678/ji-shu-qi-by-leetcode-solution-xuwj/
来源:力扣(LeetCode)
相关推荐
syzyc19 分钟前
[ABC267F] Exactly K Steps
数据结构·动态规划·题解
向阳逐梦1 小时前
PID控制算法理论学习基础——单级PID控制
人工智能·算法
2zcode1 小时前
基于Matlab多特征融合的可视化指纹识别系统
人工智能·算法·matlab
Owen_Q1 小时前
Leetcode百题斩-二分搜索
算法·leetcode·职场和发展
矢志航天的阿洪2 小时前
蒙特卡洛树搜索方法实践
算法
草莓熊Lotso2 小时前
【数据结构初阶】--顺序表(二)
c语言·数据结构·经验分享·其他
汤姆爱耗儿药2 小时前
数据结构——散列表
数据结构·散列表
UnderTheTime2 小时前
2025 XYD Summer Camp 7.10 筛法
算法
zstar-_2 小时前
Claude code在Windows上的配置流程
笔记·算法·leetcode
圆头猫爹2 小时前
第34次CCF-CSP认证第4题,货物调度
c++·算法·动态规划