【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)
相关推荐
冠位观测者18 分钟前
【Leetcode 每日一题 - 补卡】1534. 统计好三元组
数据结构·算法·leetcode
明月看潮生23 分钟前
青少年编程与数学 02-016 Python数据结构与算法 25课题、量子算法
python·算法·青少年编程·量子计算·编程与数学
weixin_4450547230 分钟前
力扣刷题-热题100题-第35题(c++、python)
c++·python·leetcode
JNU freshman1 小时前
C. Robin Hood in Town思考与理解
算法
GZX墨痕1 小时前
从零学习直接插入排序
c语言·数据结构·排序算法
Susea&1 小时前
数据结构初阶:双向链表
c语言·开发语言·数据结构
Net_Walke1 小时前
【C数据结构】 TAILQ双向有尾链表的详解
c语言·数据结构·链表
_x_w2 小时前
【17】数据结构之图及图的存储篇章
数据结构·python·算法·链表·排序算法·图论
anscos2 小时前
Actran声源识别方法连载(二):薄膜模态表面振动识别
人工智能·算法·仿真软件·actran
-优势在我2 小时前
LeetCode之两数之和
算法·leetcode