【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)
相关推荐
yuannl104 分钟前
图的存储方式
数据结构
泷寂28 分钟前
最小生成树 (MST基础)
算法
Daniel_12343 分钟前
数组——总结篇
算法
不懒不懒1 小时前
【针对路面识别数据集,结合三轴加速度标准化数据及多路面识别需求,以下是算法选择与处理方案】
算法
Reart1 小时前
Leetcode 121. 买卖股票的最佳时机(717)
后端·算法
会编程的小孩1 小时前
初识数据类型以及变量定义
数据结构·算法
Reart2 小时前
Leetcode 337.打家劫舍3(717)
后端·算法
梅梅绵绵冰2 小时前
数据结构-时间复杂度
数据结构·算法
遥感知识服务2 小时前
盐碱地、白屋顶和裸土都很亮,卫星怎样分清?
人工智能·算法·机器学习
可编程芯片开发2 小时前
基于PID控制器的车辆控制系统simulink建模与仿真
算法